# Script to run all of the pieces 
library(pacman)
p_load(
  here, fst, data.table, tictoc, furrr
)

# Download GPS data: requires environment variables: 
#   GCE_DEFAULT_PROJECT_ID, GCE_AUTH_FILE
# We have posted the output of this 
# "Data/google-project-sunroof/project-sunroof-census_tract.csv"
# "Data/google-project-sunroof/project-sunroof-postal_code.csv"
#tic('Download GPS data')
#  source(here('R/project-sunroof-download.R'))
#toc()

# Installation price regressions: 1 min
tic('Panel installatiion price regression')
  source(here('R/install-price-panel-reg.R'))
toc()

# Descriptive figures: 30s
tic('Descriptive figs')
  source(here('R/descriptive-maps.R'))
toc()

# Downloading CEMS data: Only need 2019 data
# We post output of this
# "Data/electricity-generation/cems/raw_cems_2019.fst"
# Can run this code to get additional years
#tic("Download raw CEMS data")
#  source(here('R/power-plants/00a-download-ampd.R'))
#  source(here('R/power-plants/00b-combine-ampd.R'))
#toc()

# Setting up power plant model fit
source(here('R/02-power-plants/00c-plant-info-oge.R'))
source(here('R/02-power-plants/01-excess-load-oge.R'))
source(here('R/02-power-plants/02-merge-cems-load-oge.R'))
source(here('R/02-power-plants/03-fit-unit-elec-gen-oge.R'))
source(here('R/02-power-plants/04-plant-emissions-rates-oge.R'))
source(here('R/02-power-plants/05-marginal-damages-oge.R'))
# Power plant model fit 
tic('Full Power Plant Pipeline')
# First cleaning plant info table: 25s
  tic('0: Clean plant info')
  clean_plant_info()
  toc()
# Now calculating excess load by region: 16s
  tic('1: Excess load')
  excess_load_region()
  toc()
# Merge hourly plant data with excess load: 4min
  tic('2: Prep hourly data')
  merge_plant_load() 
  toc()
# Fit unit model: 25mins
  tic('3: Fit unit model')
  count_plants()
  no_cores = availableCores()-1
  plan(multisession, workers = no_cores)
  fit_models_all_units(delete = TRUE)
  plan(sequential)
  clean_model_results()
  toc()
# Calculate emissions rates: 4mins
  tic('4: Emissions rates')
  calc_avg_emissions_rates()
  estimate_marginal_emissions_rate()
  toc()
# Calculate marginal damages: 3s
  tic('5: Marginal damages')
  # Converting 2020 SCC $ to 2014
  calc_marginal_damages(SOCIAL_COST_OF_CARBON =  51*0.7993) 
  calc_marginal_damages(SOCIAL_COST_OF_CARBON = 185*0.7993)
  calc_marginal_damages(SOCIAL_COST_OF_CARBON = 190*0.7993)
  calc_marginal_damages(SOCIAL_COST_OF_CARBON = 413*0.7993)
  toc()
# Visualize the results: 197 mins
  tic("6: Visualize results") 
  # Power plant summary tables 
  source(here('R/02-power-plants/power-plant-summary-tables.R'))
  # Main model fit plots 
  source(here('R/02-power-plants/06-visualize-results-oge.R'))
  # Out of sample model fit plots (2020)
  source(here('R/02-power-plants/07-out-of-sample.R'))
  # Simulate marginal damages ~20 mins
  source(here('R/02-power-plants/08-sim-marginal-damages.R'))
  toc()
toc()
